#!/sbin/openrc-run
supervisor=supervise-daemon

description="A Distributed RESTful Search Engine."

instance_name="${RC_SVCNAME#elasticsearch.}"
instance_name="${instance_name/elasticsearch/_default}"

name="Elasticsearch"
[ "$instance_name" != "_default" ] && name="$name ($instance_name)"

: ${user:="elastico"}
: ${group:="$(id -gn $user)"}

: ${conf_dir:="/etc/elasticsearch/${instance_name#_default}"}
: ${home_dir:="/var/lib/elasticsearch/$instance_name"}
: ${default_data_dir:="$home_dir/data"}
: ${default_plugins_dir:="$home_dir/plugins"}
: ${default_logs_dir:="/var/log/elasticsearch/${instance_name#_default}"}
: ${default_script_dir:="$conf_dir/scripts"}
: ${default_work_dir:="/var/tmp/elasticsearch/$instance_name"}
: ${create_logs_dir:="yes"}
: ${error_log:="$default_logs_dir/error.log"}

elastic_opts="
	-Epath.data=$default_data_dir
	-Epath.logs=$default_logs_dir
	$elastic_opts
	"

java_opts="
	-Des.path.home='$home_dir'
	-Des.default.path.plugins='$default_plugins_dir'
	-Des.default.path.work='$default_work_dir'
	-Des.default.path.script='$default_script_dir'
	$java_opts
	"

# env variable for: -XX:MaxDirectMemorySize
# export ES_DIRECT_SIZE=
export ES_JAVA_OPTS="$java_opts"
export ES_JVM_OPTIONS="$conf_dir/jvm.options"
export ES_PATH_CONF="$conf_dir"

command="/usr/share/java/elasticsearch/bin/elasticsearch"
command_args="$elastic_opts"
command_user="$user:$group"
command_background="yes"
output_log="/dev/null"
pidfile="/run/$RC_SVCNAME.sd.pid"

depends() {
	use net
	after firewall
}

in_contr() {
	grep "container=" /proc/1/environ
}

start_pre() {
	local dir

	# Note: checkpath doesn't create intermediate directories.
	for dir in "$home_dir" "$default_data_dir" "$default_work_dir" "$default_plugins_dir" "$default_script_dir"; do
		mkdir -p "$(dirname "$dir")"
	done

	checkpath -d -o $user:$group -m755 "$home_dir"
	checkpath -d -o $user:$group -m700 "$(dirname "$home_dir")"
	checkpath -d -o $user:$group -m700 "$default_data_dir"
	checkpath -d -o $user:$group -m700 "$default_work_dir"
	checkpath -d -o $user:$group -m700 "$default_plugins_dir"
	checkpath -d "$default_script_dir"

	if yesno "$create_logs_dir"; then
		mkdir -p "$default_logs_dir"
		checkpath -d -o $user:$group -m755 "$default_logs_dir"
	fi

	if [ -n "$max_fd" ]; then
		if [ -z "$(in_contr)" ]; then
			ulimit -n "$max_fd" && einfo "Max open filedescriptors: $max_fd"
		else
			einfo "Run 'ulimit -n $max_fd' on the container host"
		fi
	fi

	if [ -n "$max_map_count" ]; then
		if [ -z "$(in_contr)" ]; then
			sysctl -q -w vm.max_map_count="$max_map_count" && einfo "vm.max_map_count: $max_map_count"
		else
			einfo "Run 'sysctl -w vm.max_map_count=$max_map_count' on the container host"
		fi
	fi
}
